//
//  RemindersViewController.m
//  Reminders
//
//  Created by Nearsoft User on 8/2/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "RemindersViewController.h"
#import "ReminderCell.h"
#import "ReminderDetailView.h"
#import "ReminderModalDetailView.h"
#import "TestFlight.h"

@interface RemindersViewController ()

@end

@implementation RemindersViewController

@synthesize remindersDone;

#pragma mark - Deafult Methods
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [self reloadTable];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    reminders = [[NSMutableArray alloc] init];

    if (connect == nil)
        connect = [[Connection alloc] init];

    if (dateString == nil)
        dateString = [[DateStrings alloc] init];

    // Sets the add button at the navigation bar
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addReminder)];

    self.title = self.parentViewController.tabBarItem.title;

    self.tableView.separatorColor = [UIColor lightGrayColor];
    self.tableView.backgroundColor = [UIColor colorWithRed:205.0f/255.0f green:205.0f/255.0f blue:205.0f/255.0f alpha:1.0f];
}

- (void)viewDidUnload
{
    [super viewDidUnload];

    reminders = nil;
    connect = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table View Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Retuns the number of sections in the table
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Returns the number of elements in the reminders array
    return reminders.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    ReminderCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        // Loads the nib named ReminderCell as a custom cell
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ReminderCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    // Sets the labels within the custom cell
    [cell setReminder:[reminders objectAtIndex:indexPath.row]];

    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [cell setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"cellBackground.png"]]];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65; // Returns the height of the cells in the table view
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES; // Retuns YES if the cells in the table are aditable
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView beginUpdates];

    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        // Calls the removeReminder method sending a reminder from the array as a parameter
        [self removeReminder:[reminders objectAtIndex:indexPath.row]];

        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:YES];
    }  

    [tableView endUpdates];
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Sends a reminder from the array to the editReminder method
    [self editReminder:[reminders objectAtIndex:indexPath.row]];
}

#pragma mark - Reminder Methods
/**
 * Method name: addReminder
 * Description: calls the ReminderDetailView to create a new reminder
 * Parameters: 
 */
- (void)addReminder
{
    ReminderDetailView *newReminderView = [[ReminderDetailView alloc] initWithNibName:@"ReminderDetailView" bundle:[NSBundle mainBundle]];
    newReminderView.edit = NO;
    self.tabBarController.title = @"Back";

    // Pushes in the new ReminderDetailView view to add a new reminder
    [self.navigationController pushViewController:newReminderView animated:YES];
}

/**
 * Method name: editReminder
 * Description: calls the ReminderDetailView to edit a reminder
 * Parameters: reminder: the reminder to be edited
 */
- (void)editReminder:(Reminder *)reminder
{
    // Creates a ReminderDetailView
    ReminderDetailView *reminderView = [[ReminderDetailView alloc] initWithNibName:@"ReminderDetailView" bundle:[NSBundle mainBundle]];

    // Sends a reminder from the array to the new view
    reminderView.reminder = reminder;
    reminderView.edit = YES;

    // Changes the title of the navigation bar to "Back"
    self.tabBarController.title = @"Back";

    // Pushes in the new ReminderDetailView view to edit the reminder
    [self.navigationController pushViewController:reminderView animated:YES];
}

/**
 * Method name: removeReminder
 * Description: calls the method within the connection class which deletes the reminder from the database, cancel its notification and removes the reminder from the array
 * Parameters: reminder: the reminder that will be deleted
 */
- (void)removeReminder:(Reminder *)reminder
{
    NSUInteger index = [reminders indexOfObject:reminder];

    if (index == NSNotFound)
        return;

    [connect deleteReminderFromDatabase:[reminder primaryKey]];
    [reminder cancelNotification];
    [reminders removeObject:reminder];
}

/**
 * Method name: sortReminders
 * Description: sorts the reminders array by date
 * Parameters:
 */
- (void)sortReminders
{
    reminders = [NSMutableArray arrayWithArray:[reminders sortedArrayUsingComparator:^NSComparisonResult(id a, id b)
    {
        NSDate *first = [(Reminder *)a date];
        NSDate *second = [(Reminder *)b date];

        return [first compare:second];
    }]];
}

/**
 * Method name: checkUncompleteRemindersst
 * Description: Get a list of the uncomplete reminders and schedule their notifications if necessary
 * Parameters:
 */
- (void)checkUncompleteReminders
{
    Reminder *rm;

    if (remindersDone == YES)
    {
        NSMutableArray *uncompleteReminders = [connect getAllReminders:!remindersDone];

        if (uncompleteReminders.count > 0)
        {
            rm = [uncompleteReminders objectAtIndex:0];
            [self presentReminderNotification:rm];
        }
    }
    else
        if (reminders.count > 0)
        {
            rm = [reminders objectAtIndex:0];
            [self presentReminderNotification:rm];
        }

    rm = nil;
}

- (void)presentReminderNotification:(Reminder *)rm
{
    if ([dateString dateIsOlderThanToday:[rm date]])
    {
        [rm scheduleNotification];

        if (rm.repeat != 0)
            [rm presentNotification];
    }
}

#pragma mark - Reload View
/**
 * Method name: reloadTable
 * Description: Get a list of the reminders, sort them by date and reloads the table view
 * Parameters:
 */
- (void)reloadTable
{
    // Reads all the reminders to an array
    reminders = [connect getAllReminders:remindersDone];

    // Sort the array by date
    [self sortReminders];

    // Reload the view
    [self.tableView reloadData];

    // Check if there is a reminder notification to be sent
    [self checkUncompleteReminders];
}

//#pragma mark - TestFlight
//- (void)launchFeedback
//{
//    [TestFlight openFeedbackView];
//}

@end
